var models = require('../db');
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var $sql = require('../sqlMap');
var upload = require('./fileupload');

//连接数据库
var conn = mysql.createConnection(models.db);

conn.connect();
//将数据以json格式返给前端
var jsonWrite = function(res, ret){  
	if (typeof ret === 'undefined') {
		res.json({
			code:'1',
			msg:'操作失败'
		})
	} else {
		res.json(ret);
	}
}

//注册接口
router.post('/addUser', (req, res) => {
	var sql = $sql.user.add;
	var params = req.body;
	// console.log(params.username)
	// console.log(params.password)

	conn.query(sql, [params.username, params.password], function(err, result){
		if (err) {
			console.log(err)
		} 
		if (result) {
			// console.log(result)
			jsonWrite(res, result);
		}
	})
})

//登录接口
router.post('/login', (req, res) => {
	var sql = $sql.user.getUserName;
	var params = req.body;
	console.log(params)

	conn.query(sql, [params.username], function(err, result){
		if (err) {
			console.log(err)
		} 
		if (result) {
			console.log(result)
			var data = result[0];
			if(data.password == params.password){
				jsonWrite(res, data);
			} else {
				jsonWrite(res, {"msg":"密码与账号不匹配！"});
			}
		} 
	})
})

//读取secondChild组件数据接口
router.get('/getMessages', (req, res) => {
	var sql = $sql.user.getMessages;

	conn.query(sql, [], (err, result) => {
		if (err) {
			console.log(err)
		} 
		if (result) {
			// console.log(result)
			jsonWrite(res, result)
		}
	})
})

//读取主页数据接口
router.get('/getHomeMsg', (req, res) => {
	var sql = $sql.user.getHomeMsg;

	conn.query(sql, [], (err, result) => {
		if (err) {
			console.log(err)
		} 
		if (result) {
			// console.log(result)
			jsonWrite(res, result)
		}
	})
})

//文件上传服务
//单个文件上传，覆盖
router.post('/upload', upload.single('avatar'), (req, res, next) => {
	if(req.file){
		res.send('文件上传成功！');
		console.log(req.file);
		console.log(req.body);
	}
})

//获取listDatas数据接口
router.get('/getListDatas', (req, res) => {
	var sql = $sql.user.getListDatas;
	// var params = req.query || req.params;
	// console.log(params)
	// var currentPage = parseInt(params.currentPage)
	// var pageSize = parseInt(params.pageSize)

	// conn.query(sql, [currentPage, pageSize], (err, result) => {
	conn.query(sql, [], (err, result) => {
		if (err) {
			console.log(err)
		} 
		if (result) {
			// console.log(result)
			jsonWrite(res, result)
		}
	})
})
//获取listPages数据接口，某一页的数据
router.get('/getListPages', (req, res) => {
	var sql = $sql.user.getListPages;
	var params = req.query;
	// console.log(params)
	var currentPage = parseInt(params.currentPage)
	var pageSize = parseInt(params.pageSize)
	conn.query(sql, [parseInt((currentPage-1)*pageSize), parseInt(pageSize)], (err, result) => {
		if (err) {
			console.log(err)
		} 
		if (result) {
			jsonWrite(res, result)
		}
	})
})

module.exports = router;